package com.baibei.ebec.follow.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.RaeTabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.ebec.follow.fragment.LastOrdersFragment;
import com.baibei.ebec.follow.fragment.ProfitCountFragment;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.LogUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.rae.swift.session.SessionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Route(path = AppRouter.ROUTE_FOLLOWER_DETAIL)
public class FollowUserDetailActivity extends BasicActivity {

    @BindView(R2.id.tab_layout)
    RaeTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.tv_title)
    TextView tvTitle;
    @BindView(R2.id.tv_username)
    TextView tvUsername;
    @BindView(R2.id.tv_follow_num)
    TextView tvFollowNum;
    @BindView(R2.id.tv_follow)
    TextView tvFollow;
    @BindView(R2.id.iv_avatar)
    RoundedImageView ivAvatar;
    private List<Fragment> fragments;
    private String[] titles;
    private FragmentAdapter adapter;
    private String followerId;
    private String userId;
    private JSONObject jsonObject;
    private AlertDialog alertDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_follow_user_detail);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public IPresenter getBasicPresenter() {
        return null;
    }

    private void initView() {

        Intent intent = getIntent();
//        WelfareRankInfo data = (WelfareRankInfo) intent.getSerializableExtra("data");
        followerId = intent.getStringExtra("followerId");
//        tvTitle.setText(data.getMobile() + "的订购");
//        followerId = data.getFollowerId();
//        tvUsername.setText(data.getMobile());
        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = userInfo.getUserId() + "";
        getData();

    }

    private void getData() {

        AppUI.loading(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL + "ddq/api/v1/query/personal/ranking";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", userId);
                map.put("followerId", followerId);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    String string = response.body().string();
                    final JSONObject jsonObject = new JSONObject(string);
                    if (!"SUCCESS".equals(jsonObject.optString("code"))) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                                AppUI.dismiss();
                            }
                        });
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            setData(jsonObject.optJSONObject("data"));
                            AppUI.dismiss();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void setData(JSONObject json) {
        if (json == null){
            ToastUtils.showShortToast("数据获取错误");
            return;
        }
//        LogUtils.e("logs114", json.toString());
//        String mobile = json.optString("mobile");
        String followNum = json.optString("stdnum");
        String userName = json.optString("userName");
        String userPic = json.optString("userPic");
        Glide.with(this).load(userPic).into(ivAvatar);
        tvUsername.setText(userName);
        tvTitle.setText(userName + "的订购");
        tvFollowNum.setText(followNum + "人正在跟TA学");
        String flg = json.optString("flg");
        tvFollow.setText("0".equals(flg) ? "+ 跟TA学赚钱" : "已跟学");
        String sumAmount = json.optString("sumamount");
        String amountRate = json.optString("amountrate");
        JSONArray jArr = json.optJSONArray("order_detail");
        ArrayList<String> upDetail = new ArrayList<>();
        ArrayList<String> downDetail = new ArrayList<>();
        for (int i = 0; i < jArr.length(); i++) {
            JSONObject job = jArr.optJSONObject(i);
            int s = job.optInt("state");
            if (s == 1) {
                upDetail.add(job.optDouble("amount") + "");
                downDetail.add("0");
            } else {
                upDetail.add("0");
                downDetail.add(job.optDouble("amount") + "");
            }
        }

        titles = new String[]{"盈利统计", "最新订单"};
        for (String title : titles) {
            tabLayout.addTab(tabLayout.newTab().setText(title));
        }
        fragments = new ArrayList<>();
        fragments.add(ProfitCountFragment.newInstance(sumAmount, amountRate, upDetail, downDetail));
        fragments.add(LastOrdersFragment.newInstance(followerId));
        adapter = new FragmentAdapter(getSupportFragmentManager());
        viewPager.setOffscreenPageLimit(fragments.size());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    public void resetData(){
        AppUI.loading(this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL + "ddq/api/v1/query/personal/ranking";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", userId);
                map.put("followerId", followerId);
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    String string = response.body().string();
                    final JSONObject jsonObject = new JSONObject(string);
                    if (!"SUCCESS".equals(jsonObject.optString("code"))) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                                AppUI.dismiss();
                            }
                        });
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            JSONObject json = jsonObject.optJSONObject("data");
                            String followNum = json.optString("stdnum");
                            String flg = json.optString("flg");
                            tvFollowNum.setText(followNum + "人正在跟TA学");
                            tvFollow.setText("0".equals(flg) ? "+ 跟TA学赚钱" : "已跟学");
                            AppUI.dismiss();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @OnClick(R2.id.iv_back)
    public void onFinishClicked() {
        finish();
    }

    @OnClick(R2.id.tv_follow)
    public void onFollowClicked() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = BuildConfig.API_BASE_URL + "ddq/api/v1/get/notget/teacher";
                OkHttpClient client = new OkHttpClient();
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", userId);
                map.put("followerId", followerId);
                map.put("type", "1");
                Gson gson = new Gson();
                String s = gson.toJson(map);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    jsonObject = new JSONObject(response.body().string());
                    if (!"SUCCESS".equals(jsonObject.optString("code"))) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShortToast(jsonObject.optString("message"));
                            }
                        });
                        return;
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            popDialog();
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void popDialog() {
        final Dialog dialog = new Dialog(this);
        Window window = dialog.getWindow();
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_follow);
        TextView tvContent = dialog.findViewById(R.id.tv_content);
        TextView tvCancel = dialog.findViewById(R.id.tv_cancel);
        TextView tvEnsure = dialog.findViewById(R.id.tv_ensure);
        tvContent.setText(jsonObject.optJSONObject("data").optString("message"));
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                resetData();
            }
        });
        tvEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                resetData();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    public class FragmentAdapter extends FragmentPagerAdapter {
        public FragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            return fragments.get(i);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }
}
